package com.kzd.btgame.main.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.tabs.TabLayout
import com.kzd.btgame.R
import com.kzd.btgame.custom.setEmptyView
import com.kzd.btgame.custom.setTransitionStatusE
import com.kzd.btgame.custom.setTransitionStatusM
import com.kzd.btgame.databinding.FragmentHomeServiceBinding
import com.kzd.btgame.jetpack.vm.HomeViewModel
import com.kzd.btgame.main.home.adapter.ServiceChildAdapter
import com.kzd.btgame.main.home.adapter.ServiceGroupAdapter
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewBindingFragment
import com.module.lemlin.owner.ownerViewModel

class HomeServiceFragment : OwnerViewBindingFragment<FragmentHomeServiceBinding>() {

    companion object {
        const val KEY_SERVICE_ACTION = "KEY_SERVICE_ACTION"
        fun newInstance(action: Int): HomeServiceFragment {
            val bundle = Bundle().apply {
                putInt(KEY_SERVICE_ACTION, action)
            }
            return HomeServiceFragment().apply {
                arguments = bundle
            }
        }
    }

    private val mAction: Int by lazy {
        arguments?.getInt(KEY_SERVICE_ACTION) ?: 0
    }

    private var mTabSelectIndex: Int = 0

    private val mTodayOnTabSelectedListener: TabLayout.OnTabSelectedListener by lazy {
        object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                mViewBinding.includeAppRefresh.rvAppRefreshBody.scrollToPosition((tab?.position ?: 0))
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) = Unit

            override fun onTabReselected(tab: TabLayout.Tab?) = Unit
        }
    }

    private val mQuickOnTabSelectedListener: TabLayout.OnTabSelectedListener by lazy {
        object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
//                val position = tab?.position ?: 0
//                if (position == 0) {
//                    return
//                }
//                mTabSelectIndex = position

                val data = mViewModel.homeServiceQuickLiveData.value
                    ?.data?.data ?: return
                val key = tab?.tag?.toString()
                    ?: return
                mServiceGroupAdapter.setNewInstance(data[key])
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) = Unit

            override fun onTabReselected(tab: TabLayout.Tab?) = Unit
        }
    }

    private val mServiceGroupAdapter: ServiceGroupAdapter by lazy {
        ServiceGroupAdapter()
    }

    private val mServiceChildAdapter: ServiceChildAdapter by lazy {
        ServiceChildAdapter()
    }

    private val mViewModel:HomeViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override val inflate: (LayoutInflater, ViewGroup?, Boolean) -> FragmentHomeServiceBinding
        get() = FragmentHomeServiceBinding::inflate

    override fun initView() {
        mViewBinding.includeAppRefresh.rvAppRefreshBody.apply {
            layoutManager = LinearLayoutManager(context)
        }.adapter = if (mAction == 2) {
            mServiceChildAdapter
        } else mServiceGroupAdapter

        when (mAction) {
            1 -> mViewBinding.tabHomeServiceKind.addOnTabSelectedListener(
                mQuickOnTabSelectedListener
            )
            2 -> mViewBinding.tabHomeServiceKind.visibility =
                View.GONE
            else -> mViewBinding.tabHomeServiceKind.addOnTabSelectedListener(
                mTodayOnTabSelectedListener
            )
        }

        mViewBinding.includeAppRefresh.mSmartRefreshLayout.setOnRefreshListener {
            initData()
        }
        mViewBinding.includeAppRefresh.mSmartRefreshLayout.setOnLoadMoreListener {
            mViewModel.homeServiceHistory(isLoadMore = true)
        }
    }

    override fun initData() {
        when (mAction) {
            1 -> mViewModel.homeServiceQuick()
            2 -> mViewModel.homeServiceHistory()
            else -> mViewModel.homeServiceToday()
        }
    }

//    private fun initData(isLoadMore:Boolean) {
//        when (mAction) {
//            1 -> viewModel.homeServiceQuick()
//            2 -> viewModel.homeServiceHistory(isLoadMore)
//            else -> viewModel.homeServiceToday()
//        }
//    }

    override fun initViewMode() {
        mViewModel.homeServiceTodayLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            response.data?.times?.let {
                fillData(it)
            }
            val data = response.data?.data
                ?: return@observe
            mServiceGroupAdapter.setNewInstance(data)
        })

        mViewModel.homeServiceQuickLiveData.observe(viewLifecycleOwner, { response ->
//            if (response.status == Status.FAILURE) {
//                toast(response.error?.msg)
//            }
            setTransitionStatusM(response, mServiceGroupAdapter, mViewBinding.includeAppRefresh.mSmartRefreshLayout, (false))
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            val keys = data.keys.toMutableList()
            if (keys.isNullOrEmpty()) {
                return@observe
            }
            fillData(keys)

            val key0 = mViewBinding.tabHomeServiceKind.getTabAt((0))
                ?.tag?.toString() ?: return@observe

            val values = data[key0]

            if (values.isNullOrEmpty()) {
                mServiceGroupAdapter.setEmptyView()
                return@observe
            }

            mServiceGroupAdapter.setNewInstance(values)

//            val title:MutableList<ServiceTitle> = mutableListOf()
//
//            for (value in data.values) {
//                title.addAll(value)
//                break
//            }
//            if (title.isNullOrEmpty()) {
//                return@observe
//            }
        })

        mViewModel.homeServiceHistoryLiveData.observe(viewLifecycleOwner, { response ->
            setTransitionStatusE(response, mServiceChildAdapter, mViewBinding.includeAppRefresh.mSmartRefreshLayout)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            val isLoadMore = response.data?.isLoadMore
                ?: return@observe
            if (isLoadMore) {
                mServiceChildAdapter.addData(data)
            } else {
                mServiceChildAdapter.setNewInstance(data)
            }
        })
    }


    private fun fillData(times: MutableList<String>) {
        mViewBinding.tabHomeServiceKind.apply {
            removeAllTabs()
            for (item in times) addTab(newTab().apply {
                val view: View = LayoutInflater.from(requireContext())
                    .inflate(R.layout.item_game_service_label, null)
                view.findViewById<TextView>(R.id.tvGameServiceLabelName)
                    .text = item
                customView = view
                tag = item
            })
            visibility = View.VISIBLE
        }
        mViewBinding.tabHomeServiceKind.getTabAt(mTabSelectIndex)?.select()
    }

}